var express = require('express');//引用express
var fs=require('fs');
//var path = require('path');
var xmlBodyParser = require('./lib/xmlBodyParser')
var app = express();//创建服务器
var cache={};//创建服务器缓存
app.engine('html', require('ejs').renderFile);

app.configure(function(){
  app.set('view engine', 'ejs');
  app.set('action', __dirname);
  app.set('views', __dirname );
  app.set('plugin', __dirname+'/plugin');
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(xmlBodyParser);
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
  app.use(express.errorHandler());
});  

//初始路由 
app_route={
	plugins:{},
	init_plugin:function(){
		var plugin_file=__dirname+'/plugin.json';
		if(!fs.existsSync(plugin_file)){
			console.log("插件配置文件不存在,不配置插件:"+plugin_file);		
			return;
		}
		var plugins=JSON.parse(fs.readFileSync(plugin_file,'utf8'));
		this.plugins=plugins;
		for(plugin in plugins){ 	
			console.log("正在加载插件:"+plugin);		
			var route_file=__dirname+"/plugin"+plugin+'/route.json';
			var routes=app_route.load_route(route_file);
			if(routes!=null){
				console.log("加载%s插件路由成功",plugin);		
				console.log("路由:"+route_file);		
				app.use(express.static(app.get('plugin')+plugin+"/public"));
				//注册路径信息
				app_route.register_route(routes,plugin);
			}else{
				console.log("加载插件路由失败:"+route_file);		
			}
			
		}
	},
	init_default_plugin:function(){
		var route_file=__dirname+'/route.json';
		var routes=app_route.load_route(route_file);
		//注册路径信息
		app_route.register_route(routes);
	},
	init:function(){ 
		this.init_plugin();
		this.init_default_plugin();
		//注册全局地址
		global.__BASE_PATH = __dirname;
		//注册404
		//app_route.register_route_404();
	},
	load_route:function(route_path){
		if(!fs.existsSync(route_path)){
			return null;
		}
		var routes=JSON.parse(fs.readFileSync(route_path,'utf8'));
		return routes;
	},
	register_route_404:function(){
		app.get('/*', function(req, res){
			res.render('404/index.html',{message:'你访问的页面不存在'});
		})
	},
	register_route:function(routes,plugin){
		var plugin_path="";
		if(plugin!=null){
			plugin_path=app.get('plugin')+plugin+"/";
		}else{
			plugin_path="./";
		}
		for(route_path in routes){ 		
			function execute(){
				var method=routes[route_path].method;	
				var view=plugin_path+"view/"+routes[route_path].view;	
				var action=plugin_path+"action/"+routes[route_path].action;
				var request_method=routes[route_path].request==null?"get":"post";	
				console.log("正在注册路径:"+route_path);	
				console.log("正在注册action:"+action);				
				console.log("正在注册路径方法:"+method);
				if(request_method=="post"){ 
					app.post(route_path, function(req, res){			
						app_route.execute_action(req, res,view,action,method);
					});
				}else{
					app.get(route_path, function(req, res){			
						app_route.execute_action(req, res,view,action,method);
					});
				}	
			}
			execute();
		}		
	},
	execute_action:function(req, res,view,action,method){
		var actionEngine=require(action);
		var data=eval("require(action)."+method+"(req, res,view,cache)");
		if(typeof(data)=="string"){
			res.redirect(data);
		}else if(data!=null){
			res.render(view, data);
		}
	}
}

app_route.init();

app.listen(18080);//监听端口

const electron = require('electron')
// Module to control application life.
const elapp = electron.app
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow

const path = require('path')
const url = require('url')

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow

function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({width: 800, height: 600})

  // and load the index.html of the app.
  /*
  mainWindow.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }))
  */
  
  mainWindow.loadURL('http://127.0.0.1:18080');

  // Open the DevTools.
  // mainWindow.webContents.openDevTools()

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
elapp.on('ready', createWindow)

// Quit when all windows are closed.
elapp.on('window-all-closed', function () {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    elapp.quit()
  }
})

elapp.on('activate', function () {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow()
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
